{% extends 'base/base.html' %}
{% load app_extras static %}
{% block extra-css %}
<link rel="stylesheet" href="{%static 'idcops/css/select2.min.css'%}">
<style>
.badge a {color: #fff !important;}
.bg-white {background-color: #fff !important; color: #000 !important;}
.badge.text-black {background: white !important;}
td[draggable="true"] {cursor: move !important;}
td.badge.over {border: 1px dashed #000 !important;}
td[name="status"] span{ cursor:pointer }
</style>
{% endblock extra-css %}
{% block title %}详情 {{meta.title}}{% endblock %}
{% block content-header %}
<h1>
  {{meta.verbose_name}}
  <small>{{request.user.onidc}} 共 {{zones.count}}个区域</small>
</h1>
{% endblock %}

{% block main-content %}

<div class="nav-tabs-custom">
    <ul class="nav nav-tabs">
    {%for zone in zones%}
      {%if zone == current_zone %}
      <li class="active"><a href="?zone_id={{zone.id}}" data-toggle="">{{zone}} <small>({{zone.description}})</small></a></li>
      {%else%}
      <li><a href="?zone_id={{zone.id}}" data-toggle="">{{zone}}</a></li>
      {%endif%}
    {%endfor%}
    {%if perms.idcops.add_zonemap %}
    <li class="hidden-sm pull-right">
      <a title="调整区域机柜分布" href="{%url 'idcops:zonemap'%}?zone_id={{current_zone.id}}&action=config" class="text-muted">
        <i class="fa fa-gear"></i>
      </a>
    </li>
    <li class="hidden-sm pull-right">
      <a title="布局区域单元格" href="{%url 'idcops:zonemap'%}?zone_id={{current_zone.id}}&action=layout" class="text-muted">
        <i class="fa fa-edit"></i>
      </a>
    </li>
    {%endif%}
    </ul>
    <div class="tab-content no-padding">
      <div class="tab-pane active" id="zone_{{current_zone.id}}">
        <div class="box-body table-responsive">
          <table class="table table-bordered text-nowarp" nowarp="nowarp">
            <tbody id="filter_rack">
              <tr>
                <th class="text-muted">机柜分类统计:</th>
                <td name="status">
                  <i data-toggle="tooltip" title="该区域一共存在的机柜个数" class="fa fa-circle-o fa-lg"></i>
                  <span name="label" value="reset"> 区域总数</span> <small><b> {{racks.count}}</b>个</small>
                </td>
                {%for s in statistics%}
                <td name="status">
                  <i data-toggle="tooltip" title="{{s.description}}" class="text-{{s.color}} fa fa-square fa-lg"></i>
                  <span name="label" value="{{s.flag}}-{{s.id}}"> {{s.text}}</span> <small><b> {{s.count|default:'0'}}</b>个</small>
                </td>
                {%endfor%}
              </tr>
              <tr>
                <th class="text-muted">按客户过滤:</th>
                <td style="vertical-align: middle;" colspan="3">
                  <select id="client-state" class="form-control">
                    <option value="">按客户信息过滤</option>
                    {%for obj in clients%}
                    <option name="client" value="{{obj.id}}">{{obj}}</option>
                    {%endfor%}
                  </select>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
        {% if form %}
        <div class="box-body">
          <div class="text-center">
            <b class="text-red">调整行和列数量，布局一个类似Excel表格的页面</b>
          </div>
            <form action="" method="POST" class="form-horizontal" id="batchnewrack">
            {% csrf_token %}
            {% for hidden in form.hidden_fields %}
            {{ hidden }}
            {% endfor %}
            <div class="box-body">
            {% for field in form.visible_fields %}
            <div class="form-group">
            <label class="col-sm-2 control-label">{{ field.label }}:</label>
            <div class="col-sm-5">
            {{ field|addcss:"form-control"}}
            </div>
            <div class="col-sm-5 help-block">
            {{ field.help_text}}
            <div class="text-red">{{ field.errors}}</div>
            </div>
            </div>
            {% endfor %}
            </div>
            <div class="box-footer">
            <button type="button" class="btn btn-default btn-sm" onclick="window.history.go(-1)">取消并返回</button>
            <button type="submit" class="btn btn-info btn-sm pull-right">提交</button>
            </div>
            </form>
        </div>
        {% endif %}
        <div class="box-body table-responsive">
        {% if not config%}
        <table class="table table-condensed table-bordered text-nowarp" width="100%" id="zonemap_detail">
            <tbody>
            {%for cell in cells%}
            {%if forloop.counter0 == cell.row%}<tr>{%endif%}
                {%if cell.rack_id%}
                <td id="cell-{{cell.id}}" width="{% widthratio 100 max_col|add:2 1 %}%"
                  class="badge bg-{{cell.rack.status.color}} {{cell.rack.style.flag}}-{{cell.rack.style_id}} {{cell.rack.status.flag}}-{{cell.rack.status_id}}" data-rackid="{{cell.rack_id}}"
                  {%if cell.rack.client_id%} title="{{cell.rack.client.name}} ({{cell.rack.client.desc}})"
                  data-rcid="{{cell.rack.client_id}}"{%endif%}>
                  <a href="{{cell.rack.get_absolute_url}}" data-toggle="modal" data-target="#modal-lg">{{cell.rack.name}}</a>
                </td>
                {%else%}
                <td id="cell-{{cell.id}}" width="{% widthratio 100 max_col|add:2 1 %}%"
                class="badge text-black" style="background-color:#fff;">{%if cell.desc%}{{cell.desc}}{%else%}----{%endif%}</td>
                {%endif%}
            {%if cell.col == max_col%}</tr>{%endif%}
            {%endfor%}
            </tbody>
        </table>
        {%else%}
        {%include 'zonemap/config.html'%}
        {%endif%}
        </div>
      </div>
    </div>
</div>

{% endblock main-content %}

{% block extra-js %}

<script src="{%static 'idcops/js/select2.min.js'%}"></script>
<script>
$(function () { $("[data-toggle='tooltip']").tooltip(); });

$(document).ready(function (){
// clear modal cache
$('body').on('hidden.bs.modal', '.modal', function () {
    $(this).removeData('bs.modal');
});
$("select").select2();

$("#filter_rack td span").click(function(){
    var val = $(this).attr('value');
    if (val == 'reset') {
      var selected = $("#zonemap_detail tbody tr td");
      if (selected.length > 0){
        selected.css('opacity','1');
        $("html, body").animate({scrollTop: $("#zonemap_detail tbody tr td:first").offset().top}, 300);
      }
    }else{
      var selected = $("#zonemap_detail tbody tr td."+val+"");
      if (selected.length > 0){
        $("#zonemap_detail tbody tr td").css('opacity', '0.2')
        selected.css('opacity', '1');
        $("html, body").animate({scrollTop: $("#zonemap_detail tbody tr td."+val+":first").offset().top}, 300);
      }
    }
  });

  $("#client-state").change(function(){
    var client = $(this).children('option:selected').attr('value');
    $("#zonemap_detail tbody tr td").css('opacity','1');
    $("#zonemap_detail tbody tr td[data-rcid!="+client+"]").css('opacity','0.2');
    $("html, body").animate({scrollTop: $("#zonemap_detail tr td[data-rcid="+client+"]:first").offset().top}, 300);
  });
  /*
  var td_count = ($("#zonemap_detail tbody tr td").length) / ($("#zonemap_detail tbody tr").length)
  */
  var tda = $("#zonemap_detail tbody tr td a");
  var w1 = tda.width();
  var w2 = tda.parent().width();
  if (w1 > w2) {
    $("body").removeAttr('class').addClass('skin-blue sidebar-mini sidebar-collapse');
    $("#zonemap_detail tbody tr td").removeAttr('width');
    $("#zonemap_detail tbody tr td").width(w1);
  }
});
</script>

{% if config %}
<script>
$(document).ready(function(){

var height1 = $("table#zonemap_detail").height();
$('table#rackswap').parent().css({'overflow-x': 'hidden', 'overflow-y':'scroll', 'width': '100%', 'height': ''+height1+'px'});
$('table#rackswap').css({'overflow': 'scroll', 'width': '100%', 'overflow-y': 'scroll', 'overflow-x':'hidden', 'height': ''+height1+'px'});

// clear modal cache
$('body').on('hidden.bs.modal', '.modal', function () {
  $(this).removeData('bs.modal');
});

function update_cell(cell_id, rack_id,cell_desc){
var csrfmiddlewaretoken = $("input[name='csrfmiddlewaretoken']").val();
var data = {'csrfmiddlewaretoken': csrfmiddlewaretoken,'rack_id':rack_id,'cell_id':cell_id,"cell_desc":cell_desc}
$.ajax({
  type: 'POST',
  dataType: 'json',
  url: "{%url 'idcops:zonemap'%}?zone_id={{zone_id}}&action=config",
  data: data,
  success: function(data){
    console.log(data);
    //return true;
  },
  error: function(error){
    console.log(error);
    //return false;
  }
});
}

var dragSrcEl = null; //拖拽源

function handleDragStart(e) {
  //在拖动操作开始时执行脚本（对象是被拖拽元素）
  // Target (this) element is the source node.
  this.style.opacity = '0.5'; //设置被拖拽元素透明度
  dragSrcEl = this; //记录被拖拽的元素
  e.dataTransfer.effectAllowed = 'move'; //被拖拽的方式，这里是移动，也可是copy
  e.dataTransfer.setData('text/html', this.innerHTML); //设置被拖拽的内容
}

function handleDragOver(e) {
  //只要元素正在合法的放置目标上拖动时，就执行脚本（对象是目标元素）
  if (e.preventDefault) {
    e.preventDefault(); // Necessary. Allows us to drop.
  }
  e.dataTransfer.dropEffect = 'move';  // See the section on the DataTransfer object.
  return false;
}

function handleDragEnter(e) {
  //当元素被拖动到一个合法的放置目标时，执行脚本（对象是目标元素）
  // this / e.target is the current hover target.
  this.classList.add('over');
}

function handleDragLeave(e) {
  //当元素离开合法的放置目标时（对象是目标元素）
  // this / e.target is previous target element.
  this.classList.remove('over');
}

function handleDrop(e) {
  //将被拖拽元素放在目标元素内时运行脚本（对象是目标元素）
  // this/e.target is current target element.
  if (e.stopPropagation) {
    e.stopPropagation(); // Stops some browsers from redirecting.
  }
  // 如果被拖拽的元素不是本身时执行的脚本
  // Don't do anything if dropping the same column we're dragging.
  if (dragSrcEl != this) {
    // 获取源和目标的标记值
    var drag_flag = $(dragSrcEl).attr('data-flag');
    var drop_flag = $(this).attr('data-flag');
    // Set the source column's HTML to the HTML of the columnwe dropped on.
    /* 这两行进行判断后执行数据交换等等，下面仅仅交换机了源和目标元素内的text文本内容
    dragSrcEl.innerHTML = this.innerHTML;
    this.innerHTML = e.dataTransfer.getData('text/html');
    */

    // 1.执行左边机柜与左边机柜交换 ！这个可以忽略，忽略表示不作任何改变！
    /* 最好不处理,避免还要处理标签内的元数据
    if (drag_flag == drop_flag == 'left_true'){
        dragSrcEl.innerHTML = this.innerHTML;
        this.innerHTML = e.dataTransfer.getData('text/html');
        //这里函数发送后台处理,
    }*/

    // 2.执行右边机柜拖拽到左边空白可直接放置的判断
    if ((drag_flag == 'right_true') && (drop_flag == 'left_true')){
        //获取源机柜号跟当前单元个id，发送后台处理；更新前台数据
        // 2.1 先执行前端交换
        dragSrcEl.innerHTML = this.innerHTML;
        this.innerHTML = e.dataTransfer.getData('text/html');
        var src_class = $(dragSrcEl).attr('class');
        var src_rackid = $(dragSrcEl).attr('data-rackid');
        var cell_id = $(this).attr('data-pk')
        $(this).attr({'data-rackid':src_rackid,'draggable':'true','data-flag':'left_false', 'class':''}).addClass(src_class);
        $(dragSrcEl).parent().remove();
        // 2.2 发送后台处理
        update_cell(cell_id, src_rackid,"");
    }

    // 3.执行右边或左边机柜拖拽到左边不可直接放置的处理
    if (((drag_flag == 'right_true')||(drag_flag == 'left_false')) && (drop_flag == 'left_false')){
        //获取源和目标的机柜号与目标单元个的id,发送后台处理；更新前台数据
        alert("位置已经被占用,请先移动占用机柜到空白区");
    }

    // 4.执行左边机柜拖拽到左边可直接放置的处理
    if ((drag_flag == 'left_false') && (drop_flag == 'left_true')){
        dragSrcEl.innerHTML = this.innerHTML;
        this.innerHTML = e.dataTransfer.getData('text/html');
        var src_class = $(dragSrcEl).attr('class');
        var src_rackid = $(dragSrcEl).attr('data-rackid');
        var src_cell_id = $(dragSrcEl).attr('data-pk');
        var cell_id = $(this).attr('data-pk');
        // 4.1 处理源单元格
        $(dragSrcEl).removeAttr('draggable data-rackid style class').addClass('badge text-black');
        $(dragSrcEl).attr({'draggable':'false','data-flag':'left_true'});
        $(dragSrcEl).html($(dragSrcEl).attr('data-row')+" x "+$(dragSrcEl).attr('data-col'));
        // 4.2 处理目标单元格
        $(this).attr({'data-rackid':src_rackid,'draggable':'true','data-flag':'left_false', 'class':''}).addClass(src_class);
        update_cell(src_cell_id, "","");
        setTimeout(function(){ update_cell(cell_id, src_rackid,"");},1000);
    }

    // 5.执行左边机柜拖拽到右边空白可直接放置的判断 ,删除左边,添加右边
    if ((drag_flag == 'left_false') && (drop_flag == 'right_true')){
        var src_class = $(dragSrcEl).attr('class');
        var src_rackid = $(dragSrcEl).attr('data-rackid');
        var src_cell_id = $(dragSrcEl).attr('data-pk');
        var this_tr = "<tr><td class="+src_class+" data-rackid="+src_rackid+" data-flag='right_true' draggable='true'>"+dragSrcEl.innerHTML+"</td></tr>";
        $(this).parent().after(this_tr);
        update_cell(src_cell_id,"","");
        $(dragSrcEl).removeAttr('draggable data-rackid style class').addClass('badge text-black');
        $(dragSrcEl).attr({'draggable':'false','data-flag':'left_true'});
        $(dragSrcEl).html($(dragSrcEl).attr('data-row')+" x "+$(dragSrcEl).attr('data-col'));
    }

    //console.log(this);

    //console.log(dragSrcEl);
  }

  return false;
}

function handleDragEnd(e) {
  //在拖动操作结束时运行脚本（对象是被拖拽元素）
  // this/e.target is the source node.
  [].forEach.call(cols, function (col) {
    col.classList.remove('over');
    col.removeAttribute('style');
  });
}

var cols = document.querySelectorAll('td.badge');
[].forEach.call(cols, function(col) {
  col.addEventListener('dragstart', handleDragStart, false);
  col.addEventListener('dragenter', handleDragEnter, false)
  col.addEventListener('dragover', handleDragOver, false);
  col.addEventListener('dragleave', handleDragLeave, false);
  col.addEventListener('drop', handleDrop, false);
  col.addEventListener('dragend', handleDragEnd, false);
});

});
</script>
{% endif %}
{% endblock extra-js %}
